package com.duolaibei.business.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseFragment;
import com.duolaibei.business.config.Constant;
import com.duolaibei.business.config.Key;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.HomePageData;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PicassoUtils;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.utils.log.LogDebug;
import com.duolaibei.business.view.App;
import com.duolaibei.business.view.activity.CollectActivity;
import com.duolaibei.business.view.activity.MyCaptureActivity;
import com.duolaibei.business.view.activity.OrderListActivity;
import com.duolaibei.business.view.activity.PerfectDataActivity;
import com.duolaibei.business.view.activity.QrcodeActivity;
import com.duolaibei.business.view.activity.ShopManageActivity;
import com.duolaibei.business.view.activity.TerminalManageActivity;
import com.duolaibei.business.view.activity.WebViewActivity;
import com.duolaibei.business.view.activity.WorkerManageActivity;
import com.duolaibei.business.view.goods.GoodsManageActivity;
import com.duolaibei.business.widget.rollviewpager.RollPagerView;
import com.duolaibei.business.widget.rollviewpager.adapter.StaticPagerAdapter;
import com.duolaibei.business.widget.rollviewpager.hintview.ColorPointHintView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhouwei.mzbanner.holder.MZViewHolder;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by xlm on 2017/10/30 0030
 * 首页信息
 */

public class HomePageFragment extends BaseFragment {

    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mTextViewTitle;
    @Inject(R.id.home_page_more)
    private ImageView mImageViewMore;
    @Inject(R.id.home_page_scan)
    private LinearLayout mLayoutScan;
    @Inject(R.id.home_page_search)
    private LinearLayout mLayoutSearch;
    @Inject(R.id.home_page_transaction_amount)
    private TextView mTextViewAmount;
    @Inject(R.id.home_page_transaction_num)
    private TextView mTextViewNum;
    @Inject(R.id.roll_view_pager)
    private RollPagerView mRollPagerView;
    @Inject(R.id.home_page_function)
    private RecyclerView mRecyclerViewFunction;
    @Inject(R.id.home_page_advance)
    private RecyclerView mRecyclerViewAds;
    @Inject(R.id.account_name)
    private TextView mViewName;
    @Inject(R.id.swiperefreshLayout)
    private SmartRefreshLayout mSmartRefreshLayout;
    private String loginType;
    @Inject(R.id.home_page_title)
    private FrameLayout frameLayout;

    private String uid;
    private String login_id;
    private String login_type;

    private static final int PERFECT_CODE = 5;

    public HomePageFragment() {

    }

    @Override
    protected void onGetArguments(Bundle bundle) {
        super.onGetArguments(bundle);
        if (bundle != null) {
            uid = bundle.getString(Constant.UID);
            login_id = bundle.getString(Constant.LOGIN_ID);
            login_type = bundle.getString(Constant.LOGIN_TYPE);
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.fragment_homepage);
    }

    @Override
    protected void initViews() {
        mLayoutBack.setVisibility(View.GONE);
        mTextViewTitle.setVisibility(View.GONE);

    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        loginType = String.valueOf(PreferenceUtil.getParam(Preferences.LOGINTYPE, ""));
        getHomePageData();
    }

    @Override
    protected void onSetListener() {
        mLayoutSearch.setOnClickListener(this);
        mLayoutScan.setOnClickListener(this);
        mImageViewMore.setOnClickListener(this);
        mSmartRefreshLayout.setEnableLoadmore(false);
        mSmartRefreshLayout.setHeaderHeight(60);
        mSmartRefreshLayout.setPrimaryColors(Color.parseColor("#e46641"));
        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getHomePageData();
            }
        });
    }

    private static final int PERMISSON_CAMERA = 0;

    private void checkPermission() {
        if (checkCameraPermission(PERMISSON_CAMERA)) {
            permissionOk();
        }
    }

    /**
     * 所有权限都已经获取
     */
    private void permissionOk() {
        Intent intent = new Intent(getActivity(), MyCaptureActivity.class);
        intent.putExtra("title", "扫一扫");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public void onCameraPermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToast("拒绝此权限，您将无法使用摄像头权限");
        }
    }

    private final int REQUEST_CODE = 0;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.home_page_more) {
            checkPermission();
            //用户昵称
        } else if (v.getId() == R.id.home_page_scan) {
            Intent intent = new Intent(getActivity(), CollectActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.home_page_search) {
            Intent intent = new Intent(getActivity(), OrderListActivity.class);
            intent.putExtra("order_type", "all");
            startActivity(intent);
        }
    }


    /**
     * 显示功能模块信息
     */
    private void controlFunction(final HomePageData mHomePageData) {
        List<String> functionNames = new ArrayList<>();
        final List<Integer> functionIcons = new ArrayList<>();
        final String[] names = new String[]{
                "收款码",
                "门店管理",
                "终端管理",
                "员工管理",
                "订单管理",
                "商品管理",
                "完善信息"
        };
        if ("shop".equals(loginType) || "terminal".equals(loginType)) {
            functionNames.addAll(Arrays.asList(names).subList(0, 1));
        } else {
            if ("merchant".equals(loginType)) {
                if ("1".equals(String.valueOf(mHomePageData.getData().getReal_status()))) {
                    functionNames.addAll(Arrays.asList(names).subList(0, 6));
                } else {
                    functionNames.addAll(Arrays.asList(names).subList(0, 7));
                }
            }
        }
        final int[] images = new int[]{
                R.mipmap.collect_money,
                R.mipmap.shop_manage,
                R.mipmap.pos_manage,
                R.mipmap.man_manage,
                R.mipmap.order_manage,
                R.mipmap.goods_manage,
                R.mipmap.info_manage
        };
        if ("shop".equals(loginType) || "terminal".equals(loginType)) {
            functionIcons.add(images[0]);
        } else {
            if ("merchant".equals(loginType)) {
                if ("1".equals(String.valueOf(mHomePageData.getData().getReal_status()))) {
                    functionIcons.add(images[0]);
                    functionIcons.add(images[1]);
                    functionIcons.add(images[2]);
                    functionIcons.add(images[3]);
                    functionIcons.add(images[4]);
                    functionIcons.add(images[5]);
                } else {
                    functionIcons.add(images[0]);
                    functionIcons.add(images[1]);
                    functionIcons.add(images[2]);
                    functionIcons.add(images[3]);
                    functionIcons.add(images[4]);
                    functionIcons.add(images[5]);
                    functionIcons.add(images[6]);
                }
            }
        }
        LogDebug.d("--------------" + functionNames.size() + "============" + functionNames.get(5));
        mRecyclerViewFunction.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mRecyclerViewFunction.setNestedScrollingEnabled(false);
        mRecyclerViewFunction.setAdapter(new CommonAdapter<String>(getActivity(),
                R.layout.item_homepage_function, functionNames) {
            @Override
            protected void convert(ViewHolder holder, String s, final int position) {
                PicassoUtils.getinstance().LoadImage(getActivity(),
                        functionIcons.get(position),
                        (ImageView) holder.getView(R.id.function_image)
                        , PicassoUtils.PICASSO_BITMAP_SHOW_NORMAL_TYPE,
                        0);
                holder.setText(R.id.function_name, names[position]);
                if (!"merchant".equals(loginType)) {
                    if (position == 1 || position == 2
                            || position == 3 || position == 4 || position == 5) {
                        holder.itemView.setVisibility(View.GONE);
                    }
                }
                if (position == 6) {
                    if ("merchant".equals(loginType)) {
                        if ("1".equals(String.valueOf(mHomePageData.getData().getReal_status()))) {
                            holder.itemView.setVisibility(View.GONE);
                        }
                    } else {
                        holder.itemView.setVisibility(View.GONE);
                    }
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        switch (position) {
                            case 0:
                                intent.setClass(getActivity(), QrcodeActivity.class);
                                startActivity(intent);
                                break;
                            case 1:
                                intent.setClass(getActivity(), ShopManageActivity.class);
                                startActivity(intent);
                                break;
                            case 2:
                                intent.setClass(getActivity(), TerminalManageActivity.class);
                                intent.putExtra("type", "all");
                                startActivity(intent);
                                break;
                            case 3:
                                intent.setClass(getActivity(), WorkerManageActivity.class);
                                intent.putExtra("type", "all");
                                startActivity(intent);
                                break;
                            case 4:
                                intent.setClass(getActivity(), OrderListActivity.class);
                                intent.putExtra("order_type", "all");
                                startActivity(intent);
                                break;
                            case 5:
                                intent.setClass(getActivity(), GoodsManageActivity.class);
                                startActivity(intent);
                                break;
                            case 6://完善信息
                                if ("0".equals(String.valueOf(mHomePageData.getData().getReal_status()))) {
                                    intent.setClass(getActivity(), PerfectDataActivity.class);
                                    startActivityForResult(intent, PERFECT_CODE);
                                } else if ("2".equals(String.valueOf(mHomePageData.getData().getReal_status()))) {
                                    showToast("正在审核中");
                                }
                                break;
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PERFECT_CODE) {
                //更新状态
                getHomePageData();
            } else if (requestCode == REQUEST_CODE) {
                LogDebug.d("-------REQUEST_CODE--------" + data.getStringExtra("result_string"));
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mRollPagerView.resume();
        getHomePageData();
    }

    /**
     * 获取首页信息
     */
    private void getHomePageData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.HOMEPAGE);
        param.add("login_type", login_type);
        param.add("uid", uid);
        if (Constant.LOGIN_SHOP.equals(login_type)
                || Constant.LOGIN_TERMINAL.equals(login_type)) {
            param.add("login_id", login_id);
        }
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().url(ApiName.API).params(param)
                .executePost(new HttpUtils.HttpListener() {
                    @Override
                    public void onException(Throwable e) {
                        super.onException(e);
                        if (CommonUtil.isForeground(getActivity())) {
                            showToast(getString(R.string.net_state));
                        }
                        mSmartRefreshLayout.finishRefresh();
                    }

                    @Override
                    public void onHttpSuccess(String string) {
                        super.onHttpSuccess(string);
                        mSmartRefreshLayout.finishRefresh();
                        if (HttpUtils.isJson(string)) {
                            ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                            if (result.getStatus() == 1) {
                                final HomePageData data = GsonUtil.GsonToBean(string, HomePageData.class);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        setHomePageData(data);
                                        controlFunction(data);
                                    }
                                });
                            } else {
                                showToast(result.getInfo());
                            }
                        } else {
                            showToast(string);
                        }
                    }
                });
    }

    /**
     * 设置首页数据
     *
     * @param data
     */
    private void setHomePageData(final HomePageData data) {
        mTextViewAmount.setText(String.valueOf(data.getData().getPay_amount()));//金额
        mTextViewNum.setText(String.valueOf(data.getData().getCount()));//笔数
        mViewName.setText(String.valueOf(App.getApp().getUserInfo().getData().getNickname()));
        final List<HomePageData.DataBean.CarouselBean> carouselBeanList = data.getData().getCarousel();
        //轮播图
//        List<View> viewList = new ArrayList<>();
//        for (int i = 0; i < carouselBeanList.size(); i++) {
//            ImageView view = new ImageView(getActivity());
//            view.setLayoutParams(new LinearLayout.LayoutParams(
//                    LinearLayout.LayoutParams.MATCH_PARENT,
//                    LinearLayout.LayoutParams.MATCH_PARENT));
//            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
//
//            PicassoUtils.getinstance().LoadImage(getActivity(), carouselBeanList.get(i).getPath(),
//                    view,
//                    R.mipmap.white_bg_range,
//                    R.mipmap.white_bg_range,
//                    PicassoUtils.PICASSO_BITMAP_SHOW_NORMAL_TYPE, 0);
//
//            viewList.add(view);
//            final int finalI = i;
//            view.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), WebViewActivity.class);
//                    intent.putExtra(Key.TITLE, "");
//                    intent.putExtra(Key.URL, String.valueOf(carouselBeanList.get(finalI).getUrl()));
//                    startActivity(intent);
//                }
//            });
//        }
        final List<BannerBean> urlList = new ArrayList<>();
        BannerBean bannerBean;
        for (HomePageData.DataBean.CarouselBean bean : carouselBeanList) {
            bannerBean = new BannerBean(String.valueOf(bean.getUrl()),
                    String.valueOf(bean.getPath()));
            urlList.add(bannerBean);
        }
        //设置播放时间间隔
        mRollPagerView.setPlayDelay(5000);
        //设置透明度
        mRollPagerView.setAnimationDurtion(500);
        //设置适配器
        mRollPagerView.setAdapter(new BannerAdapter(urlList, getActivity()));
        //设置指示器（顺序依次）
        //自定义指示器图片
        //设置圆点指示器颜色
        //设置文字指示器
        //隐藏指示器
        //mRollViewPager.setHintView(new IconHintView(this, R.drawable.point_focus, R.drawable.point_normal));
        mRollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.WHITE, Color.GRAY));

        // 设置数据
//        mMZBanner.setPages(urlList, new MZHolderCreator<BannerViewHolder>() {
//            @Override
//            public BannerViewHolder createViewHolder() {
//                return new BannerViewHolder();
//            }
//        });

//        mBannerView.startLoop(true);
//        mBannerView.setViewList(viewList);

        //功能模块
        final List<HomePageData.DataBean.AdBean> adBeanList = data.getData().getAd();
        List<String> mDatas = new ArrayList<>();
        for (int i = 0; i < adBeanList.size(); i++) {
            mDatas.add(adBeanList.get(i).getPath());
        }
        mRecyclerViewAds.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerViewFunction.setNestedScrollingEnabled(false);
        mRecyclerViewAds.setAdapter(new CommonAdapter<String>(getActivity(), R.layout.item_homepage_ads, mDatas) {
            @Override
            protected void convert(ViewHolder holder, String s, final int position) {
                PicassoUtils.getinstance().LoadImage(getActivity(), s, (ImageView) holder.getView(R.id.item_homepage_ad),
                        R.mipmap.white_bg_range,
                        R.mipmap.white_bg_range,
                        PicassoUtils.PICASSO_BITMAP_SHOW_NORMAL_TYPE, 0
                );
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String url = String.valueOf(adBeanList.get(position).getUrl());
                        if (!CommonUtil.isEmpty(url)) {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), WebViewActivity.class);
                            intent.putExtra(Key.TITLE, "");
                            intent.putExtra(Key.URL, url);
                            startActivity(intent);
                        }
                    }
                });
            }
        });
    }

    private class BannerAdapter extends StaticPagerAdapter {
        private List<BannerBean> mBeanList;
        private Context mContext;
        private ImageView mImageView;

        BannerAdapter(List<BannerBean> beanList, Context mContext) {
            this.mBeanList = beanList;
            this.mContext = mContext;
        }

        @Override
        public View getView(ViewGroup container, int position) {
            // 返回页面布局
            View view = LayoutInflater.from(mContext).inflate(R.layout.banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(View view, final int position) {
            super.onBind(view, position);
            // 数据绑定
            PicassoUtils.getinstance().LoadImage(mContext, mBeanList.get(position).getPath(),
                    mImageView,
                    R.mipmap.white_bg_range,
                    R.mipmap.white_bg_range,
                    PicassoUtils.PICASSO_BITMAP_SHOW_NORMAL_TYPE, 0);
            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String url = String.valueOf(mBeanList.get(position).getUrl());
                    if (!CommonUtil.isEmpty(url)) {
                        Intent intent = new Intent();
                        intent.setClass(mContext, WebViewActivity.class);
                        intent.putExtra(Key.TITLE, "");
                        intent.putExtra(Key.URL, url);
                        mContext.startActivity(intent);
                    }
                }
            });
        }

        @Override
        public int getCount() {
            return mBeanList.size();
        }
    }

    private static class BannerViewHolder implements MZViewHolder<BannerBean> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(final Context context, final int position, final BannerBean bean) {
            // 数据绑定
            PicassoUtils.getinstance().LoadImage(context, bean.getPath(),
                    mImageView,
                    R.mipmap.white_bg_range,
                    R.mipmap.white_bg_range,
                    PicassoUtils.PICASSO_BITMAP_SHOW_NORMAL_TYPE, 0);
            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(context, WebViewActivity.class);
                    intent.putExtra(Key.TITLE, "");
                    intent.putExtra(Key.URL, bean.getUrl());
                    context.startActivity(intent);
                }
            });
        }
    }

    private class BannerBean {
        String url;
        String path;

        public BannerBean(String url, String path) {
            this.url = url;
            this.path = path;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }
    }
//
//    @Override
//    public void onStart() {
//        super.onStart();
////        mMZBanner.start();
//    }

    @Override
    public void onPause() {
        super.onPause();
//        mMZBanner.pause();
        mRollPagerView.pause();
    }

}
